//
//  YZXTabBar.swift
//  YZXWeibo
//
//  Created by 叶周翔 on 16/7/18.
//  Copyright © 2016年 叶周翔. All rights reserved.
//

import UIKit

class YZXTabBar: UITabBar {
    // 定义一个闭包
    var callBack:(() -> Void)?
    
    // 添加中间的按钮 需要对tabbar的重新布局
    let itemCount = 5
    
    // 布局按钮
    override func layoutSubviews() {
        super.layoutSubviews()  // 一定要调用 不然会出现bug
        // 计算每一个按钮的width
        let width:CGFloat = self.bounds.size.width / CGFloat(itemCount)
        let height:CGFloat = self.bounds.size.height
        var index: Int = 0
        
        /// 遍历子控件
        for item in self.subviews{
            let className = NSClassFromString("UITabBarButton")!
            
            if item.isKindOfClass(className){
                // 设置frame
                item.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: height)
                index++
                if index == 2{
                    index++
                }
                
            }
        }
        
        // 设置按钮的frame
        button.frame = CGRect(x: 2*width, y: 0, width: width, height: height)
        
    }
   
    /// 按钮的点击事件
    func btnDidClick(){
        
        // 需求是要弹出一个控制器
        callBack?()
        
    }
    
    
    // MARK:- 懒加载按钮
    // 懒加载按钮
    lazy var button : UIButton = {
       let btn = UIButton(type: UIButtonType.Custom)
        // 设置按钮的图片
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置背景图片
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        // 添加点击事件
        btn.addTarget(self, action: "btnDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 添加到tabbar里面
        self.addSubview(btn)
        
        return btn
    }()
    
    
}
